//
//  CalendarView.m
//  RNCalendarViewManager
//
//  Created by DJ on 2019/4/10.
//  Copyright © 2019 DJ. All rights reserved.
//

#import "CalendarView.h"
#import "UIColor+HexStringColor.h"

@implementation CalendarView{
    //需要选中的日期数组
    NSArray *_dateArray;
    //日历长
    CGFloat _width;
    //日历高
    CGFloat _height;
    //颜色都为16进制
    //当天的颜色
    NSString *_todayColor;
    //选中的颜色
    NSString *_selectionColor;
    //含有事件的日期默认颜色
    NSString *_eventDefaultColor;
    //星期几的颜色
    NSString *_weekdayTextColor;
    //头部标题颜色
    NSString *_headerTitleColor;
    //日历背景颜色
    NSString *_calendarBackgroundColor;
    //边框颜色
    NSString *_borderDefaultColor;
    //标题默认颜色
    NSString *_titleDefaultColor;
    //事件图片
    UIImage *_footImage;
    //是否显示阴历
    BOOL _showLunar;
    //是否是中文
    BOOL _chinese;
    //是否显示事件
    BOOL _showEvent;
    //是否多选
    BOOL _allowsMultipleSelection;
    //是否显示正方形
    BOOL _square;
    //KVO context
    void *_KVOContext;
    //最小和最大日期
    NSArray *_minAndMaxDateArray;
}

#pragma mark 初始化
-(instancetype)init{
    if(self = [super init]){
        self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        self.dateFormatter = [[NSDateFormatter alloc] init];
        self.dateFormatter.dateFormat = @"yyyy-MM-dd";
        self.lunarFormatter = [[LunarFormatter alloc] init];
        NSLocale *chineseLocale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        self.dateFormatter.locale = chineseLocale;
        self.selectedDateArray = [NSMutableArray array];
        self.lunarCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
        self.lunarCalendar.locale = chineseLocale;
    }
    return self;
}

#pragma mark 重新布局
-(void)layoutSubviews{
    [super layoutSubviews];
}

#pragma mark 加载日历
-(void)viewDidLoad{
    self.calendar = [[FSCalendar alloc] init];
    self.calendar.backgroundColor = [UIColor colorWithHexString:_calendarBackgroundColor];
    self.calendar.frame = CGRectMake(0, 0, _width, _height);
    [self addSubview:self.calendar];
    
    self.calendar.delegate = self;
    self.calendar.dataSource = self;
    self.calendar.allowsMultipleSelection = _allowsMultipleSelection;
    self.calendar.appearance.todayColor = [UIColor colorWithHexString:_todayColor];
    self.calendar.appearance.selectionColor = [UIColor colorWithHexString:_selectionColor];
    self.calendar.appearance.eventDefaultColor = [UIColor colorWithHexString:_eventDefaultColor];
    self.calendar.appearance.weekdayTextColor = [UIColor colorWithHexString:_weekdayTextColor];
    self.calendar.appearance.headerTitleColor = [UIColor colorWithHexString:_headerTitleColor];
    self.calendar.appearance.borderDefaultColor = [UIColor clearColor];
    self.calendar.appearance.titleDefaultColor = [UIColor colorWithHexString:_titleDefaultColor];
    
    if(_chinese){
        self.calendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
    }
    if(_square){
        self.calendar.appearance.borderRadius = 0;
    }
    self.calendar.appearance.caseOptions = FSCalendarCaseOptionsWeekdayUsesDefaultCase | FSCalendarCaseOptionsWeekdayUsesUpperCase;
    [self.calendar addObserver:self forKeyPath:@"scope" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:_KVOContext];
    self.calendar.placeholderType = FSCalendarPlaceholderTypeNone;
    self.calendar.scope = FSCalendarScopeMonth;
    self.calendar.accessibilityIdentifier = @"calendar";
}

#pragma mark 上个月
-(void)jumpToLastMonth{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:previousMonth animated:YES];
}

#pragma mark 下个月
-(void)jumpToNextMonth{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:nextMonth animated:YES];
}

#pragma mark 回到今天
-(void)backToToday{
    [self.calendar setCurrentPage:[NSDate date] animated:YES];
}

#pragma mark 跳转到指定日期
-(void)jumpToSpecifiedDate:(NSString *)dateString{
    [self.calendar setCurrentPage:[self.dateFormatter dateFromString:dateString] animated:YES];
}

#pragma mark 周显示
-(void)showWeek{
    [self.calendar setScope:FSCalendarScopeWeek animated:YES];
}

#pragma mark 月显示
-(void)showMonth{
    [self.calendar setScope:FSCalendarScopeMonth animated:YES];
}

#pragma mark 添加滑动手势
-(void)addPanGesture{
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.calendar action:@selector(handleScopeGesture:)];
    panGesture.delegate = self;
    panGesture.minimumNumberOfTouches = 1;
    panGesture.maximumNumberOfTouches = 2;
    [self addGestureRecognizer:panGesture];
    self.scopeGesture = panGesture;
}

#pragma mark FSCalendar代理方法
-(NSArray<UIColor *> *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventDefaultColorsForDate:(NSDate *)date{
    if(!_showEvent){
        return nil;
    }
    if(!_dateArray){
        return nil;
    }
    NSMutableArray<UIColor *> *colors = [NSMutableArray arrayWithCapacity:_dateArray.count];
    [_dateArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [colors addObject:[UIColor colorWithHexString:self->_eventDefaultColor]];
    }];
    return colors.copy;
}

-(NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date{
    if(!_showEvent){
        return 0;
    }
    if(!_dateArray){
        return 0;
    }
    for(NSString *str in _dateArray){
        if([[self.dateFormatter stringFromDate:date] isEqualToString:str]){
            return 1;
        }
    }
    return 0;
}

-(NSArray<UIColor *> *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventSelectionColorsForDate:(NSDate *)date{
    if(!_showEvent){
        return nil;
    }
    if(!_dateArray){
        return nil;
    }
    NSMutableArray<UIColor *> *colors = [NSMutableArray arrayWithCapacity:_dateArray.count];
    [_dateArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [colors addObject:[UIColor colorWithHexString:self->_eventDefaultColor]];
    }];
    return colors.copy;
}

-(NSDate *)minimumDateForCalendar:(FSCalendar *)calendar{
    return _minAndMaxDateArray.firstObject;
}

-(NSDate *)maximumDateForCalendar:(FSCalendar *)calendar{
    return _minAndMaxDateArray.lastObject;
}

-(void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated{
    [self.delegate changeCalendarHeight:@{@"calendarHeight":@(bounds.size.height)} calendarView:self];
    self.calendar.frame = CGRectMake(0, 0, bounds.size.width, bounds.size.height);
    [self layoutIfNeeded];
}

-(void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [self.selectedDateArray addObject:[self.dateFormatter stringFromDate:date]];
    [dic setValue:[self.dateFormatter stringFromDate:date] forKey:@"date"];
    [self.delegate dateSelect:dic calendarView:self];
    NSMutableArray *selectedDates = [NSMutableArray arrayWithCapacity:calendar.selectedDates.count];
    [calendar.selectedDates enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [selectedDates addObject:[self.dateFormatter stringFromDate:obj]];
    }];
    NSLog(@"selected dates is %@",selectedDates);
    if (monthPosition == FSCalendarMonthPositionNext || monthPosition == FSCalendarMonthPositionPrevious) {
        [calendar setCurrentPage:date animated:YES];
    }
}

-(void)calendar:(FSCalendar *)calendar didDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    [self.selectedDateArray removeObject:[self.dateFormatter stringFromDate:date]];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:self.selectedDateArray forKey:@"date"];
//    [self.delegate dateSelect:dic calendarView:self];
}

-(NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date{
    if(_showLunar){
        return [self.lunarFormatter stringFromDate:date];
    }
    return nil;
}

-(void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    NSLog(@"%s %@", __FUNCTION__, [self.dateFormatter stringFromDate:calendar.currentPage]);
}

-(UIImage *)calendar:(FSCalendar *)calendar imageForDate:(NSDate *)date{
    return _footImage;
}

#pragma mark RN传回数据的Set方法
-(void)setDateArray:(NSArray *)dataArray{
    _dateArray = dataArray;
    [self viewDidLoad];
    [self addPanGesture];
}

-(void)setWidth:(CGFloat)width{
    _width = width;
}

-(void)setHeight:(CGFloat)height{
    _height = height;
}

-(void)setTodayColor:(NSString *)todayColor{
    _todayColor = todayColor;
}

-(void)setSelectionColor:(NSString *)selectionColor{
    _selectionColor = selectionColor;
}

-(void)setEventDefaultColor:(NSString *)eventDefaultColor{
    _eventDefaultColor = eventDefaultColor;
}

-(void)setWeekdayTextColor:(NSString *)weekdayTextColor{
    _weekdayTextColor = weekdayTextColor;
}

-(void)setHeaderTitleColor:(NSString *)headerTitleColor{
    _headerTitleColor = headerTitleColor;
}

-(void)setCalendarBackgroundColor:(NSString *)calendarBackgroundColor{
    _calendarBackgroundColor = calendarBackgroundColor;
}

-(void)setBorderDefaultColor:(NSString *)borderDefaultColor{
    _borderDefaultColor = borderDefaultColor;
}

-(void)setTitleDefaultColor:(NSString *)titleDefaultColor{
    _titleDefaultColor = titleDefaultColor;
}

-(void)setImageString:(NSString *)imageString{
    _footImage = [UIImage imageNamed:imageString];
}

-(void)setShowLunar:(BOOL)showLunar{
    _showLunar = showLunar;
}

-(void)setChinese:(BOOL)chinese{
    _chinese = chinese;
}

-(void)setShowEvent:(BOOL)showEvent{
    _showEvent = showEvent;
}

-(void)setAllowsMultipleSelection:(BOOL)allowsMultipleSelection{
    _allowsMultipleSelection = allowsMultipleSelection;
}

-(void)setSquare:(BOOL)square{
    _square = square;
}

-(void)setMinAndMaxDate:(NSArray *)minAndMaxDate{
    NSDate *minDate = [self.dateFormatter dateFromString:minAndMaxDate.firstObject];
    NSDate *maxDate = [self.dateFormatter dateFromString:minAndMaxDate.lastObject];
    _minAndMaxDateArray = @[minDate,maxDate];
}

#pragma mark 释放
-(void)dealloc{
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"date"];
    [defaults synchronize];
    [self.calendar removeObserver:self forKeyPath:@"scope" context:_KVOContext];
}

#pragma mark KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if(_KVOContext == context){
        FSCalendarScope oldScope = [change[NSKeyValueChangeOldKey] unsignedIntegerValue];
        FSCalendarScope newScope = [change[NSKeyValueChangeNewKey] unsignedIntegerValue];
        NSLog(@"From %@ to %@",(oldScope == FSCalendarScopeWeek?@"week":@"month"),(newScope == FSCalendarScopeWeek?@"week":@"month"));
    }
    else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark UIGestureRecognizer Delegate
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    BOOL shouldBegin = YES;
    if(shouldBegin){
        CGPoint velocity = [self.scopeGesture velocityInView:self];
        switch (self.calendar.scope) {
            case FSCalendarScopeMonth:
                return velocity.y < 0;
            case FSCalendarScopeWeek:
                return velocity.y > 0;
        }
    }
    return shouldBegin;
}

@end
